package com.xjrsoft.core.tool.utils.aiplm;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xjrsoft.common.config.AiplmConfig;
import com.xjrsoft.core.tool.utils.DateUtil;
import com.xjrsoft.core.tool.utils.IoUtil;
import com.xjrsoft.core.tool.utils.SpringUtil;
import com.xjrsoft.core.tool.utils.StringPool;
import com.xjrsoft.module.base.entity.XjrBaseAnnexesFile;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * 文生图接口调用util
 */
@Slf4j
public class AiplmUtil {

    private static AiplmConfig aiplmConfig;
    private static Gson gson;
    private static final String fileDirPath = StringPool.SLASH + "static" + StringPool.SLASH + "AIPLM_IMG" + StringPool.SLASH + DateUtil.format(new Date(), "yyyyMM");

    static {
        aiplmConfig = SpringUtil.getBean(AiplmConfig.class);
        gson = new Gson();
    }

    public static List<AiplmModelsEntiy> getAiplmModelList(){
        String result= HttpUtil.get(aiplmConfig.getAiplmApiUrl()+"sdapi/v1/sd-models", CharsetUtil.CHARSET_UTF_8);
        List<AiplmModelsEntiy> list = gson.fromJson(result, new TypeToken<List<AiplmModelsEntiy>>() {}.getType());
        return list;
    }

    /**
     * aiplm 文生图
     * @param param
     * @return
     */
    public static AiplmTxt2imgResult txt2img(AiplmTxt2imgParam param){
        try{
            HttpResponse response = HttpRequest
                    .post(aiplmConfig.getAiplmApiUrl()+"sdapi/v1/txt2img")
                    .timeout(6000000)
                    .body(gson.toJson(param))
                    .execute();
            if(200==response.getStatus()){
                return gson.fromJson(response.body(),AiplmTxt2imgResult.class);
            }else{
                log.error("AIPLM txt2img faile ===================>{}",response.body());
                return new AiplmTxt2imgResult(response.body());
            }
        }catch (Exception e){
            log.error("AIPLM txt2img error ===================>{}",e);
        }
        return null;
    }

    /**
     * base64转图片
     * @param base64Str
     * @param fileName
     */
    public static XjrBaseAnnexesFile convertBase64ToImage(String base64Str, String fileName) {
        byte[] imageBytes = Base64.getDecoder().decode(base64Str);
        try {
            XjrBaseAnnexesFile annexesFile = new XjrBaseAnnexesFile();

            ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
            BufferedImage image = ImageIO.read(bis);
            bis.close();
            File fileDir = new File(IoUtil.getProjectPath() + fileDirPath);
            if (!fileDir.exists()){
                fileDir.mkdirs();
            }
            File outputFile = new File(IoUtil.getProjectPath() +fileDirPath+ StringPool.SLASH+fileName);
            ImageIO.write(image, "png", outputFile);
            annexesFile.setFilePath(fileDirPath+ StringPool.SLASH+fileName);
            annexesFile.setFileName(fileName);
            annexesFile.setFileExtensions(StringPool.DOT +"png");
            annexesFile.setFileType("png");
            annexesFile.setFileSize(outputFile.length()+"");
            return annexesFile;
        } catch (IOException e) {
            log.error("AIPLM convertBase64ToImage error========================>",e);
        }
        return null;
    }
}
